package com.huanglejing.shanggou.activity

import android.content.Intent
import android.os.Bundle
import android.support.v4.util.ArrayMap
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.google.gson.JsonObject
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.adapter.MineShippingAdapter
import com.huanglejing.shanggou.bean.AddressListBean
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.CacheCustomerId
import com.huanglejing.shanggou.interfaces.IonSlidingViewClickListener
import com.huanglejing.shanggou.interfaces.MineShipAddressContract.MineShipAddressPresenter
import com.huanglejing.shanggou.interfaces.MineShipAddressContract.MineShipAddressView
import com.huanglejing.shanggou.presenterimpl.MineShipAddressImpl
import com.huanglejing.shanggou.utils.ToastUtils
import com.huanglejing.shanggou.utils.UIHelper
import com.jcodecraeer.xrecyclerview.ProgressStyle
import com.jcodecraeer.xrecyclerview.XRecyclerView
import kotlinx.android.synthetic.main.activity_mine_shipping_address.*
import rx.Observable


class MineShippingAddressActivity : AppBaseActivity<MineShipAddressPresenter<MineShipAddressView>, MineShipAddressView>(), MineShipAddressView, XRecyclerView.LoadingListener, IonSlidingViewClickListener {
    private var mData: ArrayList<AddressListBean> = arrayListOf()
    private var mRv: XRecyclerView? = null
    private var deleteId: String? = null
    var adapter: MineShippingAdapter? = null
    var isGetAddress: Boolean = false

    private val mEmptyView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_empty)
    }
    private val mErrorView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_error)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isGetAddress = intent?.extras?.getBoolean("isGetAddress", false)?:false
        initWidget()
    }

    override fun createPresenter(): MineShipAddressPresenter<MineShipAddressView> = MineShipAddressImpl()

    override fun getLayoutId(): Int = R.layout.activity_mine_shipping_address

    override fun requestPermission() {
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("customerId", CacheCustomerId ?: "")
        }
        return Observable.just(map)
    }

    override fun getDeleteParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("customerId", CacheCustomerId ?: "")
            put("id", deleteId ?: "")
        }
        return Observable.just(map)
    }

    private fun initWidget() {
        setAPPTitle(resources.getString(R.string.str_shipping_address))
        mRv = findViewById<XRecyclerView>(R.id.rv_shipping_address_list)
        mRv?.setPullRefreshEnabled(true)
        mRv?.setLoadingMoreEnabled(true)
        mRv?.setLoadingListener(this@MineShippingAddressActivity)
        //设置加载风格
        mRv?.setLoadingMoreProgressStyle(ProgressStyle.LineScale)
        mRv?.setRefreshProgressStyle(ProgressStyle.BallGridPulse)
        //  mRv?.addItemDecoration(new DividerItemDecoration(Test1Activity.this,DividerItemDecoration.HORIZONTAL));
        val manager = LinearLayoutManager(this@MineShippingAddressActivity, LinearLayoutManager
                .VERTICAL, false)
        mRv?.layoutManager = manager
        adapter = MineShippingAdapter(this@MineShippingAddressActivity, mData ?: arrayListOf())
        mRv?.setAdapter(adapter)

        iv_add_address.setOnClickListener {
            UIHelper.startActivity(AddAddresssActivity::class.java)
        }
    }

    override fun onResume() {
        super.onResume()
     //   onRefresh()
    }

    override fun <T> showContent(data: T?) {
        try {
            val newData = data as? ArrayList<AddressListBean>
            if (newData != null) {
                mData?.clear()
                mData?.addAll(newData)
                if (mData?.size?:0<1 && mEmptyView!=null){
                    mRv?.emptyView=mEmptyView
                }
                adapter?.setData(mData ?: arrayListOf())

            }
        } catch (e: Exception) {
            KLog.e(e?.message)
        }

    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        if (mErrorView!=null){
            mRv?.emptyView=mErrorView
            mErrorView?.setOnClickListener {
                mBasePresenter?.getAddressList()
            }
        }

        adapter?.setData(arrayListOf())
        loadComPlete()
    }


    override fun showDeleteSuccess(t: Any) {
        if (t is JsonObject) {
            if (t?.get("data")?.isJsonObject == true
                    && t?.get("status")?.asString?.equals("00") ?: false) {
                ToastUtils.toastLong( resources.getString(R.string.str_delete_address_success))
                onRefresh()
            }
        }
    }

    override fun onRefresh() {
        mBasePresenter?.getAddressList()
        loadComPlete()
    }

    override fun onLoadMore() {
        loadComPlete()
    }

    fun loadComPlete() {
        mRv?.loadMoreComplete()
        mRv?.refreshComplete()
        mRv?.setNoMore(true)
    }

    override fun onItemClick(view: View?, position: Int) {
      if (isGetAddress){
          val intent = Intent(this@MineShippingAddressActivity, SaveOrderActivity::class.java)
          val bundle = Bundle()
          bundle.putSerializable("AddressListBean", mData.get(position))
          intent.putExtras(bundle)
         setResult(200,intent)
          finish()
      }else{
          val bundle = Bundle()
          bundle.putSerializable("AddressListBean", mData.get(position))
          UIHelper.startActivity(AddAddresssActivity::class.java, bundle)
      }
    }

    /**
     * 删除item    * @param position
     */
    override fun onDeleteBtnCilck(view: View?, position: Int) {
        deleteId = mData?.get(position)?.id
        mBasePresenter?.deleteAddress()
//        mData.removeAt(position)
//        adapter?.setData(mData)
//        adapter?.notifyDataSetChanged()

    }

    override fun onSetBtnCilck(view: View?, position: Int) {

    }
}
